<?php
namespace Home\Model;
use  Think\Model;
class OrderModel extends Model{

 protected $autoCheckFields =false;

     /*******获取默认收货地址*********/
     function get_my_address($user_id)
    {
        $Users=M('users');
        $User_address=M('user_address');

       $where['user_id']=$user_id;
       $address_id=$Users->where($where)->getField('address_id');

       $field="address_id,consignee,country,province,city,district,address,mobile,tel,zipcode,best_time";
       if ($address_id) {
           $where=array();
           $where['address_id']=$address_id;
           $info=$User_address->field($field)->where($where)->find();


            $res = !empty($info['consignee']) &&
                    !empty($info['country']) &&
                    !empty($info['mobile']);

            

           if(!$info || !$res) return false;
           else 
            {
              return $info; 
            }
       }
       else
       {
           $info=$User_address->field($field)->where($where)->order('address_id desc')->find();

          

           $res = !empty($info['consignee']) &&
                    !empty($info['country']) &&
                    !empty($info['mobile']);

           if(!$info || !$res) return false;
           else return $info; 
       }
       
    }


    /**
     * 取得订单商品
     * @param   int     $order_id   订单id
     * @return  array   订单商品数组
     */
    function order_goods($order_id) {

        $sql = "SELECT  og.goods_id, og.goods_name,  og.goods_number, " .  //og.rec_id, og.goods_sn,og.market_price,
                "og.goods_price, og.goods_attr, " . //, og.is_real, og.parent_id, og.extension_code,og.is_gift
                "og.goods_price * og.goods_number AS subtotal,  g.goods_thumb " .
                "FROM " . C('DB_PREFIX') . "order_goods as og left join " . C('DB_PREFIX') . "goods g on og.goods_id = g.goods_id" .
                " WHERE og.order_id = '$order_id'";

        $res = M()->query($sql);
        foreach ($res as $row) {
            // if ($row['extension_code'] == 'package_buy') {
            //     $row['package_goods_list'] = model('PackageBase')->get_package_goods($row['goods_id']);
            // }
            $row['goods_thumb']=get_image_path($row['goods_thumb']);
            $row['subtotal']=price_format($row['subtotal']);
            $row['goods_price']=price_format($row['goods_price']);

            $goods_list[] = $row;
        }
        return $goods_list;
    }
    /**
     * 获得指定的商品属性
     *
     * @access      public
     * @param       array       $arr        规格、属性ID数组
     * @param       type        $type       设置返回结果类型：pice，显示价格，默认；no，不显示价格
     *
     * @return      string
     */
    function get_goods_attr_info($arr, $type = 'pice') {
        $attr = '';

        if (!empty($arr)) {
            // $fmt = "%s:%s[%s] \n";
             $fmt = "%s:%s[%s];";

            $sql = "SELECT a.attr_name, ga.attr_value, ga.attr_price " .
                    "FROM " . C('DB_PREFIX'). "goods_attr AS ga, " .
                    C('DB_PREFIX') . "attribute AS a " .
                    "WHERE " . db_create_in($arr, 'ga.goods_attr_id') . " AND a.attr_id = ga.attr_id";
            $res = M()->query($sql);
            foreach ($res as $row) {
                $attr_price = round(floatval($row['attr_price']), 2);
                $attr .= sprintf($fmt, $row['attr_name'], $row['attr_value'], $attr_price);
            }
            $attr = str_replace('[0]', '', $attr);
        }

        return $attr;
    }
    /**
     * 取得配送方式信息
     * @param   int     $shipping_id    配送方式id
     * @return  array   配送方式信息
     */
    function shipping_info($shipping_id) {
        if($shipping_id)
        {
          $where['shipping_id']=$shipping_id;
          $where['enabled']='1';
          $row=M('shipping')->where($where)->find();       
        }
        else
        {
          $where['enabled']='1';
          $row=M('shipping')->where($where)->order('shipping_id desc')->find(); 
        }

        return $row;
    }
     
    /**
     * 取得可用的配送方式列表
     * @param   array   $region_id_list     收货人地区id数组（包括国家、省、市、区）
     * @return  array   配送方式数组
     */
    public function available_shipping_list($region_id_list) {
        $sql = 'SELECT s.shipping_id, s.shipping_code, s.shipping_name, ' .
                's.shipping_desc, s.insure, s.support_cod, a.configure ' .
                'FROM ' . C('DB_PREFIX') . 'shipping AS s, ' .
                C('DB_PREFIX'). 'shipping_area AS a, ' .
                C('DB_PREFIX'). 'area_region AS r ' .
                'WHERE r.region_id ' . db_create_in($region_id_list) .
                ' AND r.shipping_area_id = a.shipping_area_id AND a.shipping_id = s.shipping_id AND s.enabled = 1 ORDER BY s.shipping_order';
       
        $list=M()->query($sql);
        return $list;
    }

     /**
     * 取得某配送方式对应于某收货地址的区域信息
     * @param   int     $shipping_id        配送方式id
     * @param   array   $region_id_list     收货人地区id数组
     * @return  array   配送区域信息（config 对应着反序列化的 configure）
     */
    function shipping_area_info($shipping_id, $region_id_list) {
        $sql = 'SELECT s.shipping_code, s.shipping_name, ' .
                's.shipping_desc, s.insure, s.support_cod, a.configure ' .
                'FROM ' . C('DB_PREFIX') . 'shipping AS s, ' .
                C('DB_PREFIX') . 'shipping_area AS a, ' .
                C('DB_PREFIX') . 'area_region AS r ' .
                "WHERE s.shipping_id = '$shipping_id' " .
                'AND r.region_id ' . db_create_in($region_id_list) .
                ' AND r.shipping_area_id = a.shipping_area_id AND a.shipping_id = s.shipping_id AND s.enabled = 1';
        $list = M()->query($sql);
        $row=$list[0];

        if (!empty($row)) {
            $shipping_config = unserialize_config($row['configure']);
            if (isset($shipping_config['pay_fee'])) {
                if (strpos($shipping_config['pay_fee'], '%') !== false) {
                    $row['pay_fee'] = floatval($shipping_config['pay_fee']) . '%';
                } else {
                    $row['pay_fee'] = floatval($shipping_config['pay_fee']);
                }
            } else {
                $row['pay_fee'] = 0.00;
            }
        }

        return $row;
    }

    /**
     * 获取订单第一个商品的缩略图
     * @param type $order_id
     * @return type
     */
   public function get_order_thumb($order_id) {

        $arr = M()->query("SELECT g.goods_thumb FROM " .C('DB_PREFIX') . "order_goods as og left join " . C('DB_PREFIX') . "goods g on og.goods_id = g.goods_id WHERE og.order_id = " . $order_id . " limit 1");
        return $arr[0]['goods_thumb'];
    }
/**
     * 查询订单状态
     * @access  public
     * @param   int     $order_status      订单状态
     * @param   int     $shipping_status   发货状态
     * @param   int     $pay_status        付款状态
     * @param   int     $return_status     退款/退换货状态
     * @return  array
     */
    public function get_order_status($return_status,$order_status, $shipping_status,$pay_status) {

        if($return_status>0)
        {
          switch ($return_status) {
              case 1:
                  $status_str='正在申请退款';
                  break;
             case 2:
                  $status_str='正在申请退货';
                  break;
             case 3:
                  $status_str='正在申请换货';
                  break;
             case 4:
                 if($pay_status==2)
                 {
                  $status_str='待退款';
                 }
                 else
                 {
                    $status_str='已退款';
                 }
                  
                  break;
             case 5:
                  $status_str='待退货';
                  break;
             case 6:
                  $status_str='待换货';
                  break;
              
              default:
                   $status_str='异常申请';
                  break;
          }

        }
        else if($order_status==5)
        {
            if($shipping_status==1)
            {
                 $status_str='待收货';
            }
            else
            {
                $status_str='已收货';
            }
        }
        else if($pay_status==2)
        {
            $status_str='待发货';
        }
        else if($order_status==2)
        {
            $status_str='取消';
        }
        else if($order_status==4)
        {
            $status_str='已退货';
        }
        else
        {
          $status_str='待付款';
        }

        return $status_str;

    }


/**
     * 取得订单信息
     * @param   int     $order_id   订单id（如果order_id > 0 就按id查，否则按sn查）
     * @param   string  $order_sn   订单号
     * @return  array   订单信息（金额都有相应格式化的字段，前缀是formated_）
     */
    function order_info($order_id, $order_sn = '') {
        /* 计算订单各种费用之和的语句 */
        $total_fee = " (goods_amount - discount + tax + shipping_fee + insure_fee + pay_fee + pack_fee + card_fee) AS total_fee ";
        $order_id = intval($order_id);

        $field="order_id,order_sn,user_id,order_status,shipping_status,pay_status,return_status"
                .",consignee,province,city,district,address,mobile as mobile_phone,postscript"
                .",pay_id,pay_name,mobile_pay,mshop_id,commission"
                .",order_amount,shipping_fee,pay_fee,bonus,money_paid"
                .",add_time,pay_time,shipping_time "
                .",shipping_id,shipping_name,invoice_no";

        // $field='*';
        if ($order_id > 0) {
            $sql = "SELECT $field, " 
                     . $total_fee . " FROM " . C('DB_PREFIX') .
                    "order_info WHERE is_deleted=0 and order_id = '$order_id'";
        } else {
            $sql = "SELECT $field, " 
                     . $total_fee . "  FROM " . C('DB_PREFIX') .
                    "order_info WHERE is_deleted=0 and order_sn = '$order_sn'";
        }


        $list=M()->query($sql);
        $order = $list[0];

         //判断合计--减去红包的
        if($order['money_paid']>0)
        {
          $order['total_fee']=$order['money_paid'];
        }
        else if($order['order_amount']<$order['total_fee'])
        {
          $order['total_fee']=$order['order_amount'];
        }

        $order['bonus']=$order['bonus']?$order['bonus']:0;//红包

        /* 格式化金额字段 */
        if ($order) {
            // $order['formated_goods_amount'] = price_format($order['goods_amount'], false);
            // $order['formated_discount'] = price_format($order['discount'], false);
            // $order['formated_tax'] = price_format($order['tax'], false);
            // $order['formated_shipping_fee'] = price_format($order['shipping_fee'], false);
            // $order['formated_insure_fee'] = price_format($order['insure_fee'], false);
            // $order['formated_pay_fee'] = price_format($order['pay_fee'], false);
            // $order['formated_pack_fee'] = price_format($order['pack_fee'], false);
            // $order['formated_card_fee'] = price_format($order['card_fee'], false);
            $order['formated_total_fee'] = price_format($order['total_fee'], false);
            // $order['formated_money_paid'] = price_format($order['money_paid'], false);
            // $order['formated_bonus'] = price_format($order['bonus'], false);
            // $order['formated_integral_money'] = price_format($order['integral_money'], false);
            // $order['formated_surplus'] = price_format($order['surplus'], false);
            // $order['formated_order_amount'] = price_format(abs($order['order_amount']), false);
            $order['add_time_date'] = local_date(2, $order['add_time']);
        }

        return $order;
    }

      /**
     * 取得可用的支付方式列表
     * @param   bool    $support_cod        配送方式是否支持货到付款
     * @param   int     $cod_fee            货到付款手续费（当配送方式支持货到付款时才传此参数）
     * @param   int     $is_online          是否支持在线支付
     * @return  array   配送方式数组
     */
    function available_payment_list($support_cod, $cod_fee = 0, $is_online = false) {
        $sql = 'SELECT pay_id, pay_code, pay_name, pay_fee, pay_desc, pay_config, is_cod' .
                ' FROM ' . C('DB_PREFIX') .
                'touch_payment WHERE enabled = 1 ';
        if (!$support_cod) {
            $sql .= 'AND is_cod = 0 '; // 如果不支持货到付款
        }
        if ($is_online) {
            $sql .= "AND is_online = '1' ";
        }
        $sql .= 'ORDER BY pay_order'; // 排序
        $res =M()->query($sql);

        $pay_list = array();
        foreach ($res as $key => $row) {
            if ($row['is_cod'] == '1') {
                $row['pay_fee'] = $cod_fee;
            }
            $row['format_pay_fee'] = strpos($row['pay_fee'], '%') !== false ? $row['pay_fee'] :
                    price_format($row['pay_fee'], false);
            $modules[] = $row;
        }
        if (isset($modules)) {
            return $modules;
        }
    }

        /**
     * 取得支付方式信息
     * @param   int     $pay_id     支付方式id
     * @return  array   支付方式信息
     */
    function payment_info($pay_id) {
        $sql = 'SELECT * FROM ' . C('DB_PREFIX') .
                "touch_payment WHERE pay_id = '$pay_id' AND enabled = 1";
        $list=M()->query($sql);

        return $list[0];
    }
/**
     * 添加商品到购物车
     *
     * @access  public
     * @param   integer $goods_id   商品编号
     * @param   integer $num        商品数量
     * @param   array   $spec       规格值对应的id数组
     * @param   integer $parent     基本件
     */
    function addto_cart($session,$goods_id, $num = 1, $spec = array(), $parent = 0) {

        $_parent_id = $parent;
        $user_id=$session['user_id'];
        $DB_PREFIX=C('DB_PREFIX');

        $result=array('code'=>0,'mes'=>'');



        /* 取得商品信息 */
        $sql = "SELECT g.goods_name, g.goods_sn, g.is_on_sale, g.is_real,g.cat_id, " .
                "g.market_price, g.shop_price AS org_price, g.promote_price, g.promote_start_date, " .
                "g.promote_end_date, g.goods_weight, g.integral, g.extension_code, " .
                "g.goods_number, g.is_alone_sale, g.is_shipping," .
                "IFNULL(mp.user_price, g.shop_price * '$session[discount]') AS shop_price " .
                " FROM " . $DB_PREFIX . "goods AS g " .
                " LEFT JOIN " . $DB_PREFIX . "member_price AS mp " .
                "ON mp.goods_id = g.goods_id AND mp.user_rank = '$session[user_rank]' " .
                " WHERE g.goods_id = '$goods_id'" .
                " AND g.is_delete = 0";
        $list=M()->query($sql);
        $goods =$list[0];

        if (empty($goods)) {
            $result['mes']='没有商品';
            $result['code']=20002;
            return $result;
        }

        /* 如果是作为配件添加到购物车的，需要先检查购物车里面是否已经有基本件 */
        // if ($parent > 0) {
        //     $sql = "SELECT COUNT(*) as count FROM " . $DB_PREFIX .
        //             "cart WHERE goods_id='$parent' AND user_id='" . $user_id . "' AND extension_code <> 'package_buy'";
        //     $list=M()->query($sql);
        //     $res = $list[0];
        //     if ($res['count'] == 0) {
        //          $result['mes']='不存在配件';
        //          $result['code']=1;;

        //         return $result;
        //     }
        // }

        //不加属性的商品价格
        $org_shop_price=$goods['org_price'];

        /* 是否正在销售 */
        if ($goods['is_on_sale'] == 0) {
            $result['mes']='商品已下架';
            $result['code']=20002;
            return $result;
        }

        /* 不是配件时检查是否允许单独销售 */
        if (empty($parent) && $goods['is_alone_sale'] == 0) {
            $result['mes']='单独销售不允许';
            $result['code']=20002;
            return $result;
        }

        /* 如果商品有规格则取规格商品信息 配件除外 */
        $sql = "SELECT * FROM " .$DB_PREFIX . "products WHERE goods_id = '$goods_id' LIMIT 0, 1";
        $list = M()->query($sql);

        $prod=$list[0];

        if (D('GoodsBase')->is_spec($spec) && !empty($prod)) {
            $product_info = D('ProductsBase')->get_products_info($goods_id, $spec);
        }
        if (empty($product_info)) {
            $product_info = array('product_number' => '', 'product_id' => 0);
        }

        /* 检查：库存 */
        $use_storage=M('shop_config')->where("code='use_storage'")->getField('value');
        if ($use_storage == 1) {
            //检查：商品购买数量是否大于总库存
            if ($num > $goods['goods_number']) {
               $result['mes']='商品库存不足';
               $result['code']=50001;

                return $result;
            }

            //商品存在规格 是货品 检查该货品库存
            if (D('GoodsBase')->is_spec($spec) && !empty($prod)) {
                if (!empty($spec)) {
                    /* 取规格的货品库存 */
                    if ($num > $product_info['product_number']) {
                        $result['mes']='货品库存不足，请选择其他属性';
                        $result['code']=50002;
                        return $result;
                    }
                }
            }
        }

        /* 计算商品的促销价格 */
        $spec_price = D('Goods')->spec_price($spec);
        $goods_price = D('GoodsBase')->get_final_price($session,$goods_id, $num, true, $spec);



        
        $goods['market_price'] += $spec_price;
        $goods_attr = $this->get_goods_attr_info($spec);
        // print_r($spec);exit();
        $goods_attr_id = join(',', $spec);

        /* 计算商品的佣金 */
         $profit_rate = D('Category')->get_cat_rate( $goods['cat_id']);
         $profit_rate =$profit_rate?$profit_rate:0;

        /* 初始化要插入购物车的基本件数据 */
        $parent = array(
            'user_id' => $user_id,
            'session_id' => 0,
            'goods_id' => $goods_id,
            'goods_sn' => addslashes($goods['goods_sn']),
            'product_id' => $product_info['product_id'],
            'goods_name' => addslashes($goods['goods_name']),
            'market_price' => $goods['market_price'],
            'goods_attr' => addslashes($goods_attr),
            'goods_attr_id' => $goods_attr_id,
            'org_shop_price' =>$org_shop_price,
            'is_real' => $goods['is_real'],
            'extension_code' => $goods['extension_code'],
            'is_gift' => 0,//是否是赠品，0，否；其他，是参加优惠活动的id，取值于ecs_favourable_activity 的act_id
            'is_shipping' => $goods['is_shipping'],
            'rec_type' => 0,//rec_type tinyint 购物车商品类型,0,普通;1,团够;2,拍卖;3,夺宝奇兵 
            'profit_rate' => $profit_rate
        );
   
        /* 如果该配件在添加为基本件的配件时，所设置的“配件价格”比原价低，即此配件在价格上提供了优惠， */
        /* 则按照该配件的优惠价格卖，但是每一个基本件只能购买一个优惠价格的“该配件”，多买的“该配件”不享 */
        /* 受此优惠 */
        $basic_list = array();
        $sql = "SELECT parent_id, goods_price " .
                "FROM " . $DB_PREFIX.
                "group_goods WHERE goods_id = '$goods_id'" .
                " AND goods_price < '$goods_price'" .
                " AND parent_id = '$_parent_id'" .
                " ORDER BY goods_price";
        $res = M()->query($sql);
        foreach ($res as $row) {
            $basic_list[$row['parent_id']] = $row['goods_price'];
        }
        /* 取得购物车中该商品每个基本件的数量 */
        $basic_count_list = array();
        if ($basic_list) {
            $sql = "SELECT goods_id, SUM(goods_number) AS count " .
                    "FROM " . $DB_PREFIX .
                    "cart WHERE user_id = '" . $user_id . "'" .
                    " AND parent_id = 0" .
                    " AND extension_code <> 'package_buy' " .
                    " AND goods_id " . db_create_in(array_keys($basic_list)) .
                    " GROUP BY goods_id";
            $res =  M()->query($sql);
            foreach ($res as $row) {
                $basic_count_list[$row['goods_id']] = $row['count'];
            }
        }

        /* 取得购物车中该商品每个基本件已有该商品配件数量，计算出每个基本件还能有几个该商品配件 */
        /* 一个基本件对应一个该商品配件 */
        if ($basic_count_list) {
            $sql = "SELECT parent_id, SUM(goods_number) AS count " .
                    "FROM " . $DB_PREFIX .
                    "cart WHERE user_id = '" . $user_id . "'" .
                    " AND goods_id = '$goods_id'" .
                    " AND extension_code <> 'package_buy' " .
                    " AND parent_id " . db_create_in(array_keys($basic_count_list)) .
                    " GROUP BY parent_id";
            $res = M()->query($sql);
            foreach ($res as $row) {
                $basic_count_list[$row['parent_id']] -= $row['count'];
            }
        }

        /* 循环插入配件 如果是配件则用其添加数量依次为购物车中所有属于其的基本件添加足够数量的该配件 */
        foreach ($basic_list as $parent_id => $fitting_price) {
            /* 如果已全部插入，退出 */
            if ($num <= 0) {
                break;
            }

            /* 如果该基本件不再购物车中，执行下一个 */
            if (!isset($basic_count_list[$parent_id])) {
                continue;
            }

            /* 如果该基本件的配件数量已满，执行下一个基本件 */
            if ($basic_count_list[$parent_id] <= 0) {
                continue;
            }

            /* 作为该基本件的配件插入 */
            $parent['goods_price'] = max($fitting_price, 0) + $spec_price; //允许该配件优惠价格为0
            $parent['goods_number'] = min($num, $basic_count_list[$parent_id]);
            $parent['parent_id'] = $parent_id;
            $parent['creat_at'] = time();
            /* 添加 */
            M('cart')->add($parent);
            /* 改变数量 */
            $num -= $parent['goods_number'];
        }

        /* 如果数量不为0，作为基本件插入 */
        if ($num > 0) {
            /* 检查该商品是否已经存在在购物车中 */
            $sql = "SELECT goods_number FROM " . $DB_PREFIX .
                    "cart WHERE user_id = '" . $user_id . "' AND goods_id = '$goods_id' " .
                    " AND parent_id = 0 AND goods_attr = '" . $this->get_goods_attr_info($spec) . "' " .
                    " AND extension_code <> 'package_buy' " .
                    " AND rec_type = '0'";
            $list=M()->query($sql);
            $row =$list[0];

            if ($row) { //如果购物车已经有此物品，则更新
                $num += $row['goods_number'];
                if (D('GoodsBase')->is_spec($spec) && !empty($prod)) {
                    $goods_storage = $product_info['product_number'];
                } else {
                    $goods_storage = $goods['goods_number'];
                }

                if ($use_storage == 0 || $num <= $goods_storage) {
                    $goods_price = D('GoodsBase')->get_final_price($session,$goods_id, $num, true, $spec);
                    $sql = "UPDATE " . $DB_PREFIX. "cart SET goods_number = '$num'" .
                            " , goods_price = '$goods_price',profit_rate = '$profit_rate',creat_at = ".gmtime().",org_shop_price='$org_shop_price' 
                              WHERE user_id = '" . $user_id . "' AND goods_id = '$goods_id' " .
                            " AND parent_id = 0 AND goods_attr = '" . $this->get_goods_attr_info($spec) . "' " .
                            " AND extension_code <> 'package_buy' " .
                            "AND rec_type = '0'";
                    M()->execute($sql);
                } else {
                    $result['mes']='货品库存不足，请选择其他属性';
                    $result['code']=50001;
                    return $result;
                }
            } else { //购物车没有此物品，则插入

                $goods_price = D('GoodsBase')->get_final_price($session,$goods_id, $num, true, $spec);
                $parent['goods_price'] = max($goods_price, 0);
                $parent['goods_number'] = $num;
                $parent['parent_id'] = 0;
                $parent['creat_at'] = gmtime();

                M('cart')->add($parent);
            }
        }

        /* 把赠品删除 */
        // $sql = "DELETE FROM " . $DB_PREFIX . "cart WHERE user_id = '" . $user_id . "' AND is_gift <> 0";
        //  M()->execute($sql);

        return $result;
    }
  /**
     * 更新购物车
     *
     * @access  public
     * @param   integer $goods_id   商品编号
     * @param   integer $num        商品数量
     * @param   array   $spec       规格值对应的id数组
     * @param   integer $rec_id     购物车ID
     */
    function updateto_cart($session,$goods_id, $num = 1, $spec = array(), $rec_id = 0) {
        $rec_where['rec_id']=$rec_id;
        if(!$rec_id){ $result['mes']='购物车ID不能为空';$result['code']=20002;return $result;} 

        $_parent_id =0;
        $user_id=$session['user_id'];
        $DB_PREFIX=C('DB_PREFIX');

        $result=array('code'=>0,'mes'=>'');



        /* 取得商品信息 */
        $sql = "SELECT g.goods_name, g.goods_sn, g.is_on_sale, g.is_real,g.cat_id, " .
                "g.market_price, g.shop_price AS org_price, g.promote_price, g.promote_start_date, " .
                "g.promote_end_date, g.goods_weight, g.integral, g.extension_code, " .
                "g.goods_number, g.is_alone_sale, g.is_shipping," .
                "IFNULL(mp.user_price, g.shop_price * '$session[discount]') AS shop_price " .
                " FROM " . $DB_PREFIX . "goods AS g " .
                " LEFT JOIN " . $DB_PREFIX . "member_price AS mp " .
                "ON mp.goods_id = g.goods_id AND mp.user_rank = '$session[user_rank]' " .
                " WHERE g.goods_id = '$goods_id'" .
                " AND g.is_delete = 0";



      

        $list=M()->query($sql);
        $goods =$list[0];

        $org_shop_price=$goods['org_price'];

        if (empty($goods)) {
            $result['mes']='没有商品';
            $result['code']=20002;
            return $result;
        }



        /* 是否正在销售 */
        if ($goods['is_on_sale'] == 0) {
            $result['mes']='商品已下架';
            $result['code']=20002;
            return $result;
        }

        /* 不是配件时检查是否允许单独销售 */
        if (empty($parent) && $goods['is_alone_sale'] == 0) {
            $result['mes']='单独销售不允许';
            $result['code']=20002;
            return $result;
        }

        /* 如果商品有规格则取规格商品信息 配件除外 */
        $sql = "SELECT * FROM " .$DB_PREFIX . "products WHERE goods_id = '$goods_id' LIMIT 0, 1";
        $list = M()->query($sql);

        $prod=$list[0];

        if (D('GoodsBase')->is_spec($spec) && !empty($prod)) {
            $product_info = D('ProductsBase')->get_products_info($goods_id, $spec);
        }
        if (empty($product_info)) {
            $product_info = array('product_number' => '', 'product_id' => 0);
        }

        /* 检查：库存 */
        $use_storage=M('shop_config')->where("code='use_storage'")->getField('value');
        if ($use_storage == 1) {
            //检查：商品购买数量是否大于总库存
            if ($num > $goods['goods_number']) {
               $result['mes']='商品库存不足';
               $result['code']=50001;

                return $result;
            }

            //商品存在规格 是货品 检查该货品库存
            if (D('GoodsBase')->is_spec($spec) && !empty($prod)) {
                if (!empty($spec)) {
                    /* 取规格的货品库存 */
                    if ($num > $product_info['product_number']) {
                        $result['mes']='货品库存不足，请选择其他属性';
                        $result['code']=50002;
                        return $result;
                    }
                }
            }
        }

        /* 计算商品的促销价格 */
        $spec_price = D('Goods')->spec_price($spec);
        $goods_price = D('GoodsBase')->get_final_price($session,$goods_id, $num, true, $spec);



        
        $goods['market_price'] += $spec_price;
        $goods_attr = $this->get_goods_attr_info($spec);
       
        $goods_attr_id = join(',', $spec);

        /* 计算商品的佣金 */
         $profit_rate = D('Category')->get_cat_rate( $goods['cat_id']);
         $profit_rate =$profit_rate?$profit_rate:0;

        /* 初始化要插入购物车的基本件数据 */
        $parent = array(
            // 'user_id' => $user_id,
            'session_id' => 0,
            // 'goods_id' => $goods_id,
            'goods_sn' => addslashes($goods['goods_sn']),
            'product_id' => $product_info['product_id'],
            'goods_name' => addslashes($goods['goods_name']),
            'market_price' => $goods['market_price'],
            'goods_attr' => addslashes($goods_attr),
            'goods_attr_id' => $goods_attr_id,
            'org_shop_price' =>$org_shop_price,
            'is_real' => $goods['is_real'],
            'extension_code' => $goods['extension_code'],
            'is_gift' => 0,//是否是赠品，0，否；其他，是参加优惠活动的id，取值于ecs_favourable_activity 的act_id
            'is_shipping' => $goods['is_shipping'],
            'rec_type' => 0,//rec_type tinyint 购物车商品类型,0,普通;1,团够;2,拍卖;3,夺宝奇兵 
            'profit_rate' => $profit_rate
        );
   
        /* 如果该配件在添加为基本件的配件时，所设置的“配件价格”比原价低，即此配件在价格上提供了优惠， */
        /* 则按照该配件的优惠价格卖，但是每一个基本件只能购买一个优惠价格的“该配件”，多买的“该配件”不享 */
        /* 受此优惠 */
        // $basic_list = array();
        // $sql = "SELECT parent_id, goods_price " .
        //         "FROM " . $DB_PREFIX.
        //         "group_goods WHERE goods_id = '$goods_id'" .
        //         " AND goods_price < '$goods_price'" .
        //         " AND parent_id = '$_parent_id'" .
        //         " ORDER BY goods_price";
        // $res = M()->query($sql);
        // foreach ($res as $row) {
        //     $basic_list[$row['parent_id']] = $row['goods_price'];
        // }
        // /* 取得购物车中该商品每个基本件的数量 */
        // $basic_count_list = array();
        // if ($basic_list) {
        //     $sql = "SELECT goods_id, SUM(goods_number) AS count " .
        //             "FROM " . $DB_PREFIX .
        //             "cart WHERE user_id = '" . $user_id . "'" .
        //             " AND parent_id = 0" .
        //             " AND extension_code <> 'package_buy' " .
        //             " AND goods_id " . db_create_in(array_keys($basic_list)) .
        //             " GROUP BY goods_id";
        //     $res =  M()->query($sql);
        //     foreach ($res as $row) {
        //         $basic_count_list[$row['goods_id']] = $row['count'];
        //     }
        // }

        // /* 取得购物车中该商品每个基本件已有该商品配件数量，计算出每个基本件还能有几个该商品配件 */
        // /* 一个基本件对应一个该商品配件 */
        // if ($basic_count_list) {
        //     $sql = "SELECT parent_id, SUM(goods_number) AS count " .
        //             "FROM " . $DB_PREFIX .
        //             "cart WHERE user_id = '" . $user_id . "'" .
        //             " AND goods_id = '$goods_id'" .
        //             " AND extension_code <> 'package_buy' " .
        //             " AND parent_id " . db_create_in(array_keys($basic_count_list)) .
        //             " GROUP BY parent_id";
        //     $res = M()->query($sql);
        //     foreach ($res as $row) {
        //         $basic_count_list[$row['parent_id']] -= $row['count'];
        //     }
        // }

        // /* 循环插入配件 如果是配件则用其添加数量依次为购物车中所有属于其的基本件添加足够数量的该配件 */
        // foreach ($basic_list as $parent_id => $fitting_price) {
        //     /* 如果已全部插入，退出 */
        //     if ($num <= 0) {
        //         break;
        //     }

        //     /* 如果该基本件不再购物车中，执行下一个 */
        //     if (!isset($basic_count_list[$parent_id])) {
        //         continue;
        //     }

        //     /* 如果该基本件的配件数量已满，执行下一个基本件 */
        //     if ($basic_count_list[$parent_id] <= 0) {
        //         continue;
        //     }

        //     /* 作为该基本件的配件插入 */
        //     $parent['goods_price'] = max($fitting_price, 0) + $spec_price; //允许该配件优惠价格为0
        //     $parent['goods_number'] = min($num, $basic_count_list[$parent_id]);
        //     $parent['parent_id'] = $parent_id;
        //     $parent['creat_at'] = time();
        //     /* 添加 */
        //     M('cart')->add($parent);
        //     /* 改变数量 */
        //     $num -= $parent['goods_number'];
        // }

        /* 如果数量不为0，作为基本件插入 */
        if ($num > 0) {
                $goods_price = D('GoodsBase')->get_final_price($session,$goods_id, $num, true, $spec);


                $parent['goods_price']=$goods_price;
                $parent['goods_number']=$num;
                $parent['creat_at']=gmtime();

                M("cart")->where("rec_id='$rec_id'")->save($parent);
                
                $result['mes']='改变购物车商品成功';
                $result['code']=0;
                return $result;
        }
        else
        {
                $result['mes']='数量不能小于0';
                $result['code']=20002;
                return $result;
        }

        /* 把赠品删除 */
        // $sql = "DELETE FROM " . $DB_PREFIX . "cart WHERE user_id = '" . $user_id . "' AND is_gift <> 0";
        //  M()->execute($sql);


    }

  /**
     * 获得购物车中的商品
     *
     * @access  public
     * @return  array
     */
    function get_cart_goods($session) {
        /* 初始化 */
        $goods_list = array();
        $total = array(
            'goods_price' => 0, // 本店售价合计（有格式）
            // 'market_price' => 0, // 市场售价合计（有格式）
            // 'saving' => 0, // 节省金额（有格式）
            // 'save_rate' => 0, // 节省百分比
            'goods_amount' => 0, // 本店售价合计（无格式）
            'total_number' => 0,
        );
        /* 循环、统计 */
        $field="rec_id,goods_id,goods_sn,product_id,goods_name,goods_price,goods_number,goods_attr,is_shipping,is_real,goods_attr_id,parent_id,org_shop_price";
        $sql = "SELECT $field, IF(parent_id, parent_id, goods_id) AS pid " .
                " FROM " .C('DB_PREFIX') . "cart " .
                " WHERE user_id = '" . $session['user_id'] . "' AND rec_type = '0'" .
                " ORDER BY creat_at desc,pid, parent_id";
        $res=M()->query($sql);

        // print_r($sql);exit();

        /* 用于统计购物车中实体商品和虚拟商品的个数 */
        $virtual_goods_count = 0;
        $real_goods_count = 0;
        foreach ($res as $row) {
            $total['total_number']+=$row['goods_number'];
            $total['goods_price'] += $row['goods_price'] * $row['goods_number'];
            
            $row['subtotal_price'] =$row['goods_price'] * $row['goods_number'];
            $row['subtotal'] = price_format($row['subtotal_price'], false);

            $row['goods_price'] = price_format($row['goods_price'], false);

             $row['formated_org_shop_price'] = price_format($row['org_shop_price'], false);

            if($row['creat_at'])
            $row['creat_at'] = date('Y-m-d H:i:s',$row['creat_at']);
            /* 统计实体商品和虚拟商品的个数 */
            if ($row['is_real']) {
                $real_goods_count++;
            } else {
                $virtual_goods_count++;
            }

            /* 查询规格 */
            // if (trim($row['goods_attr']) != '') {
            //     $row['goods_attr'] = addslashes($row['goods_attr']);
            //     $sql = "SELECT attr_value FROM " .C('DB_PREFIX') . "goods_attr WHERE goods_attr_id " .
            //             db_create_in($row['goods_attr_id']);
            //     $attr_list = M()->query($sql);
            //     foreach ($attr_list as $attr) {
            //         $row['goods_name'] .= ' [' . $attr['attr_value'] . '] ';
            //     }
            // }
            /* 增加是否在购物车里显示商品图 */

                $list =M()->query("SELECT `goods_thumb` FROM " . C('DB_PREFIX') . "goods WHERE `goods_id`='{$row['goods_id']}'");
                $res=$list[0];
                $goods_thumb = $res['goods_thumb'];
                $row['goods_thumb'] = get_image_path($goods_thumb);

            // if ($row['extension_code'] == 'package_buy') {
            //     $row['package_goods_list'] = D('PackageBase')->get_package_goods($row['goods_id']);
            // }
            //获取库存
            $row['goods_max_number'] ==0;
            $row['is_lack'] =0;
            if($row['product_id'])
            {
                 $product_spec=explode(',',$row['goods_attr_id']);
                 if($product_spec)
                 {
                     $product_info = D('ProductsBase')->get_products_info($row['goods_id'], $product_spec);
                     $row['goods_max_number'] = $product_info['product_number'];                       
                 }

            }
            else
            {
                $list =M()->query("SELECT `goods_number` FROM " . C('DB_PREFIX') . "goods WHERE `goods_id`='{$row['goods_id']}'");
                $res=$list[0];
                $row['goods_max_number'] = $res['goods_number'];             
            }
            //是否库存不足
            if($row['goods_max_number']<$row['goods_number'])$row['is_lack']=1;

            $goods_list[] = $row;
        }
        $total['goods_amount'] = $total['goods_price'];
        // $total['saving'] = price_format($total['market_price'] - $total['goods_price'], false);
        // if ($total['market_price'] > 0) {
        //     $total['save_rate'] = $total['market_price'] ? round(($total['market_price'] - $total['goods_price']) *
        //                     100 / $total['market_price']) . '%' : 0;
        // }
        $total['goods_price'] = price_format($total['goods_price'], false);
        // $total['market_price'] = price_format($total['market_price'], false);
        // $total['real_goods_count'] = $real_goods_count;
        // $total['virtual_goods_count'] = $virtual_goods_count;

        return array('goods_list' => $goods_list, 'total' => $total);
    }
  
 /**
     * 取得购物车商品
     * @param   int     $type   类型：默认普通商品
     * @return  array   购物车商品数组
     */
    function cart_goods($session,$type =0,$arr) {


        $user_id=$session['user_id'];
       

        $sql = "SELECT rec_id, user_id, goods_id , goods_name, goods_sn, goods_number  , " .
                "market_price, goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, is_shipping, " .
                "goods_price * goods_number AS subtotal " .
                "FROM " . C('DB_PREFIX').
                "cart WHERE user_id = '" . $user_id . "' ".
                " AND rec_type = '$type' ";


                if(!empty($arr))
                    $sql.= " AND rec_id  ".db_create_in($arr);


        $arr = M()->query($sql);

        /* 格式化价格及礼包商品 */
        foreach ($arr as $key => $value) {
            $arr[$key]['formated_goods_price'] = price_format($value['goods_price'], false);
            $arr[$key]['formated_subtotal'] = price_format($value['subtotal'], false);
            $list =M()->query("SELECT `goods_thumb` FROM " . C('DB_PREFIX') . "goods WHERE `goods_id`='{$value['goods_id']}'");
            $res=$list[0];
            $goods_thumb = $res['goods_thumb'];
            $arr[$key]['goods_img'] = get_image_path($goods_thumb);

            // if ($value['extension_code'] == 'package_buy') {
            //     $arr[$key]['package_goods_list'] = model('PackageBase')->get_package_goods($value['goods_id']);
            // }
        }

        return $arr;
    }
 /**
     * 获得订单信息
     *
     * @access  private
     * @return  array
     */
    function flow_order_info($flow_order=array(),$flow_type=0) {
        $order =$flow_order? $flow_order : array();

        /* 初始化配送和支付方式 */
        if (!isset($order['shipping_id']) || !isset($order['pay_id'])) {
            /* 如果还没有设置配送和支付 */
            if ($_SESSION['user_id'] > 0) {
                /* 用户已经登录了，则获得上次使用的配送和支付 */
                $arr = D('Order')->last_shipping_and_payment($user_id);

                if (!isset($order['shipping_id'])) {
                    $order['shipping_id'] = $arr['shipping_id'];
                }
                if (!isset($order['pay_id'])) {
                    $order['pay_id'] = $arr['pay_id'];
                }
            } else {
                if (!isset($order['shipping_id'])) {
                    $order['shipping_id'] = 0;
                }
                if (!isset($order['pay_id'])) {
                    $order['pay_id'] = 0;
                }
            }
        }
        $order['shipping_id']=$order['shipping_id'] ?$order['shipping_id'] :8;//默认

        if (!isset($order['pack_id'])) {
            $order['pack_id'] = 0;  // 初始化包装
        }
        if (!isset($order['card_id'])) {
            $order['card_id'] = 0;  // 初始化贺卡
        }
        if (!isset($order['bonus'])) {
            $order['bonus'] = 0;    // 初始化红包
        }
        if (!isset($order['integral'])) {
            $order['integral'] = 0; // 初始化积分
        }
        if (!isset($order['surplus'])) {
            $order['surplus'] = 0;  // 初始化余额
        }

        /* 扩展信息 */


        return $order;
    }

    /**
     * 获得上一次用户采用的支付和配送方式
     *
     * @access  public
     * @return  void
     */
    function last_shipping_and_payment($user_id) {
        $sql = "SELECT shipping_id, pay_id " .
                " FROM " .C('DB_PREFIX') .
                "order_info WHERE user_id = '$user_id' " .
                " ORDER BY order_id DESC LIMIT 1";
        $list = M()->query($sql);
        $row=$list[0];

        if (empty($row)) {
            /* 如果获得是一个空数组，则返回默认值 */
            $row = array('shipping_id' => 0, 'pay_id' => 0);
        }

        return $row;
    }

        /**
     * 取得红包信息
     * @param   int     $bonus_id   红包id
     * @param   string  $bonus_sn   红包序列号
     * @param   array   红包信息
     */
    function bonus_info($user_id,$bonus_id, $bonus_sn = '') {
        $sql = "SELECT t.*, b.* " .
                "FROM " . C('DB_PREFIX') . "bonus_type AS t," .
                C('DB_PREFIX')  . "user_bonus AS b " .
                "WHERE t.type_id = b.bonus_type_id ";
        if ($bonus_id > 0) {
            $sql .= " and user_id='$user_id' AND b.bonus_id = '$bonus_id' limit 1";
        } else {
            $sql .= "AND b.bonus_sn = '$bonus_sn' limit 1";
        }
        $list=M()->query($sql);

        return  $list[0];
    }


    /**
     * 取得用户当前可用红包
     * @param   int     $user_id        用户id
     * @param   float   $goods_amount   订单商品金额
     * @return  array   红包数组
     */
    function user_bonus($user_id, $goods_amount = 0) {
        $day = getdate();
        $today = local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);

        $sql = "SELECT t.type_name, t.type_money, b.bonus_id " .//t.type_id, 
                "FROM " . C('DB_PREFIX') . "bonus_type AS t," .
                C('DB_PREFIX'). "user_bonus AS b " .
                "WHERE t.type_id = b.bonus_type_id " .
                "AND t.use_start_date <= '$today' " .
                "AND t.use_end_date >= '$today' " .
                "AND t.min_goods_amount <= '$goods_amount' " .
                "AND b.user_id<>0 " .
                "AND b.user_id = '$user_id' " .
                "AND b.order_id = 0 ".
                " order by t.type_money desc ";
        return M()->query($sql);
    }

 /**
     * 获得购物车中商品的总重量、总价格、总数量
     *
     * @access  public
     * @param   int     $type   类型：默认普通商品
     * @return  array
     */
    function cart_weight_price($rec_ids,$type =0) {

        if(empty($rec_ids))
            return array();

        $user_id=$session['user_id'];
        $package_row['weight'] = 0;
        $package_row['amount'] = 0;
        $package_row['number'] = 0;

        $packages_row['free_shipping'] = 1;

        /* 计算超值礼包内商品的相关配送参数 */
        $sql = 'SELECT goods_id, goods_number, goods_price FROM '
         . C('DB_PREFIX') . "cart WHERE extension_code = 'package_buy' AND user_id = '" . $user_id . "' and rec_id ".db_create_in($rec_ids);
        $row = $this->query($sql);

        if ($row) {
            $packages_row['free_shipping'] = 0;
            $free_shipping_count = 0;

            foreach ($row as $val) {
                // 如果商品全为免运费商品，设置一个标识变量
                $sql = 'SELECT count(*) as count FROM ' .
                        C('DB_PREFIX')  . 'package_goods AS pg, ' .
                        C('DB_PREFIX') . 'goods AS g ' .
                        "WHERE g.goods_id = pg.goods_id AND g.is_shipping = 0 AND pg.package_id = '" . $val['goods_id'] . "'";
                $list = M()->query($sql);
                $res=$list[0];
                $shipping_count = $res['count'];

                if ($shipping_count > 0) {
                    // 循环计算每个超值礼包商品的重量和数量，注意一个礼包中可能包换若干个同一商品
                    $sql = 'SELECT SUM(g.goods_weight * pg.goods_number) AS weight, ' .
                            'SUM(pg.goods_number) AS number FROM ' .
                            C('DB_PREFIX') . 'package_goods AS pg, ' .
                            C('DB_PREFIX'). 'goods AS g ' .
                                "WHERE g.goods_id = pg.goods_id AND g.is_shipping = 0 AND pg.package_id = '" . $val['goods_id'] . "'";
                    $list = M()->query($sql);
                    $goods_row=$list[0];

                    $package_row['weight'] += floatval($goods_row['weight']) * $val['goods_number'];
                    $package_row['amount'] += floatval($val['goods_price']) * $val['goods_number'];
                    $package_row['number'] += intval($goods_row['number']) * $val['goods_number'];
                } else {
                    $free_shipping_count++;
                }
            }

            $packages_row['free_shipping'] = $free_shipping_count == count($row) ? 1 : 0;
        }

        /* 获得购物车中非超值礼包商品的总重量 */
        $sql = 'SELECT SUM(g.goods_weight * c.goods_number) AS weight, ' .
                'SUM(c.goods_price * c.goods_number) AS amount, ' .
                'SUM(c.goods_number) AS number ' .
                'FROM ' . C('DB_PREFIX') . 'cart AS c ' .
                'LEFT JOIN ' . C('DB_PREFIX') . 'goods AS g ON g.goods_id = c.goods_id ' .
                "WHERE rec_id ".db_create_in($rec_ids).
                " AND rec_type = '$type' AND g.is_shipping = 0 AND c.extension_code != 'package_buy'";
        $list = M()->query($sql);
        $row=$list[0];

        $packages_row['weight'] = floatval($row['weight']) + $package_row['weight'];
        $packages_row['amount'] = floatval($row['amount']) + $package_row['amount'];
        $packages_row['number'] = intval($row['number']) + $package_row['number'];
        /* 格式化重量 */
        $packages_row['formated_weight'] = formated_weight($packages_row['weight']);

        return $packages_row;
    }



 /**
     * 计算购物车中的商品能享受红包支付的总额
     * @return  float   享受红包支付的总额
     */
    function compute_discount_amount($rec_ids) {
        /* 查询优惠活动 */
        $now = gmtime();
        $user_rank = ',' . $session['user_rank'] . ',';
        $sql = "SELECT *" .
                "FROM " . C('DB_PREFIX').
                "favourable_activity WHERE start_time <= '$now'" .
                " AND end_time >= '$now'" .
                " AND CONCAT(',', user_rank, ',') LIKE '%" . $user_rank . "%'" .
                " AND act_type " . db_create_in(array('2', '1'));
        $favourable_list = M()->query($sql);
        if (!$favourable_list) {
            return 0;
        }

        /* 查询购物车商品 */
        $sql = "SELECT c.goods_id, c.goods_price * c.goods_number AS subtotal, g.cat_id, g.brand_id " .
                "FROM " . C('DB_PREFIX') . "cart AS c, " . C('DB_PREFIX'). "goods AS g " .
                "WHERE c.goods_id = g.goods_id " .
                "AND c.rec_id = '" . db_create_in($rec_ids) . "' " .
                "AND c.parent_id = 0 " .
                "AND c.is_gift = 0 " .
                "AND rec_type = '0'";
        $goods_list =M()->query($sql);
        if (!$goods_list) {
            return 0;
        }

        /* 初始化折扣 */
        $discount = 0;
        $favourable_name = array();

        /* 循环计算每个优惠活动的折扣 */
        foreach ($favourable_list as $favourable) {
            $total_amount = 0;
            if ($favourable['act_range'] == 0) {
                foreach ($goods_list as $goods) {
                    $total_amount += $goods['subtotal'];
                }
            } elseif ($favourable['act_range'] == 1) {
                /* 找出分类id的子分类id */
                $id_list = array();
                $raw_id_list = explode(',', $favourable['act_range_ext']);
                foreach ($raw_id_list as $id) {
                    $id_list = array_merge($id_list, array_keys(cat_list($id, 0, false)));
                }
                $ids = join(',', array_unique($id_list));

                foreach ($goods_list as $goods) {
                    if (strpos(',' . $ids . ',', ',' . $goods['cat_id'] . ',') !== false) {
                        $total_amount += $goods['subtotal'];
                    }
                }
            } elseif ($favourable['act_range'] == 2) {
                foreach ($goods_list as $goods) {
                    if (strpos(',' . $favourable['act_range_ext'] . ',', ',' . $goods['brand_id'] . ',') !== false) {
                        $total_amount += $goods['subtotal'];
                    }
                }
            } elseif ($favourable['act_range'] == 3) {
                foreach ($goods_list as $goods) {
                    if (strpos(',' . $favourable['act_range_ext'] . ',', ',' . $goods['goods_id'] . ',') !== false) {
                        $total_amount += $goods['subtotal'];
                    }
                }
            } else {
                continue;
            }
            if ($total_amount > 0 && $total_amount >= $favourable['min_amount'] && ($total_amount <= $favourable['max_amount'] || $favourable['max_amount'] == 0)) {
                if ($favourable['act_type'] == 2) {
                    $discount += $total_amount * (1 - $favourable['act_type_ext'] / 100);
                } elseif ($favourable['act_type'] == 1) {
                    $discount += $favourable['act_type_ext'];
                }
            }
        }


        return $discount;
    }
    /**
     * 取得购物车该赠送的积分数
     * @return  int     积分数
     */
    function get_give_integral($rec_ids) {
        


        $rec_str='';
        if ($rec_ids) {
            $rec_str=" and c.rec_id ".db_create_in($rec_ids);
        }
        else
        {
            return 0;
        }
        $sql = "SELECT SUM(c.goods_number * IF(g.give_integral > -1, g.give_integral, c.goods_price))" .
                " as count FROM " .C('DB_PREFIX') . "cart AS c, " .
                C('DB_PREFIX') . "goods AS g " .
                "WHERE c.goods_id = g.goods_id " .
                $rec_str .
                "AND c.goods_id > 0 " .
                "AND c.parent_id = 0 " .
                "AND c.rec_type = 0 " .
                "AND c.is_gift = 0";
        $res = M()->query($sql);
        return intval($res[0]['count']);
    }
    /**
     * 取得订单该赠送的积分数
     * @return  int     积分数
     */
    function get_order_give_integral($order_id) {
        
        if (!$order_id) {
            return 0;
        }

        $sql = "SELECT SUM(c.goods_number * IF(g.give_integral > -1, g.give_integral, c.goods_price))" .
                " as count FROM " .C('DB_PREFIX') . "order_goods AS c, " .
                C('DB_PREFIX') . "goods AS g " .
                "WHERE c.goods_id = g.goods_id " .
                " and c.order_id='$order_id'" .
                "AND c.goods_id > 0 " .
                "AND c.parent_id = 0 " .
                "AND c.is_gift = 0";
        $res = M()->query($sql);
        return intval($res[0]['count']);
    }
 /**
     * 取得当前用户应该得到的红包总额
     */
    function get_total_bonus($rec_ids) {



        $day = getdate();
        $today = local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);


        /* 按商品发的红包 */
        $sql = "SELECT SUM(c.goods_number * t.type_money)" .
                " as count FROM " . C('DB_PREFIX') . "cart AS c, "
                . C('DB_PREFIX') . "bonus_type AS t, "
                . C('DB_PREFIX'). "goods AS g " .
                "WHERE " .
                " c.is_gift = 0 " .
               " and c.rec_id ".db_create_in($rec_ids).
                " AND c.goods_id = g.goods_id " .
                "AND g.bonus_type_id = t.type_id " .
                "AND t.send_type = '1' " .
                "AND t.send_start_date <= '$today' " .
                "AND t.send_end_date >= '$today' " .
                "AND c.rec_type = '0'";
        $list = M()->query($sql);
        $res=$list[0];

        $goods_total = floatval($res['count']);

        /* 取得购物车中非赠品总金额 */
        $sql = "SELECT SUM(goods_price * goods_number) " .
                " as count FROM " . C('DB_PREFIX') .
                "cart WHERE " .
                "  is_gift = 0 " .
                 " and rec_id ".db_create_in($rec_ids).
                " AND rec_type = '0'";
        $list = M()->query($sql);
        $res=$list[0];
        $amount = floatval($res['count']);

        /* 按订单发的红包 */
        $sql = "SELECT FLOOR('$amount' / min_amount) * type_money " .
                "as count FROM " . C('DB_PREFIX') .
                "bonus_type WHERE send_type = '2' " .
                " AND send_start_date <= '$today' " .
                "AND send_end_date >= '$today' " .
                "AND min_amount > 0 ";
        $list = M()->query($sql);
        $res=$list[0];
        $order_total = floatval($res['count']);

        return $goods_total + $order_total;
    

}
 /**
     * 赋给当前用户 -订单得到的红包
     */
    function add_order_total_bonus($order_id,$user_id,$amount=0) {



        $day = getdate();
        $today = local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);
        $num=0;//赠送红包数量


        /* 按商品发的红包 */
        $sql = "SELECT t.type_id,c.goods_number" .
                " as count FROM " . C('DB_PREFIX') . "order_goods AS c, "
                . C('DB_PREFIX') . "bonus_type AS t, "
                . C('DB_PREFIX'). "goods AS g " .
                "WHERE " .
                " c.is_gift = 0 " .
               " and c.order_id='$order_id' ".
                " AND c.goods_id = g.goods_id " .
                "AND g.bonus_type_id = t.type_id " .
                "AND t.send_type = '1' " .
                "AND t.send_start_date <= '$today' " .
                "AND t.send_end_date >= '$today' " ;
        $list = M()->query($sql);
        //开始赠送红包
        $user_bonus=M("user_bonus");
        foreach ($list as $key => $value) {
            $add_data=array();
            $add_data['bonus_type_id']=$value['type_id'];
            $add_data['user_id']=$user_id;
            $user_bonus->add($add_data);
            $num++;
        }



        


  
        

        /* 按订单发的红包 */
        $sql = "SELECT type_id " .
                " FROM " . C('DB_PREFIX') .
                "bonus_type WHERE send_type = '2' " .
                " AND send_start_date <= '$today' " .
                "AND send_end_date >= '$today' " .
                "AND min_amount > 0 ".
                " and min_amount<$amount".
                " order by min_amount desc limit 1";  
        $list = M()->query($sql);
        $bonus_info=$list[0];//只有订单金额最大的红包 优先赠送
       
        //开始赠送红包
        $add_data=array();
        $add_data['bonus_type_id']=$bonus_info['type_id'];
        $add_data['user_id']=$user_id;
        $n=$user_bonus->add($add_data);
        $num++;
        

        return $num;
    

}


 /**
     * 取得购物车总金额
     * @params  boolean $include_gift   是否包括赠品
     * @param   int     $type           类型：默认普通商品
     * @return  float   购物车总金额
    */
    function cart_amount($rec_ids='',$include_gift=true,$type=0)
    {
        if(!$rec_ids)return 0;
        
                $sql = "SELECT SUM(goods_price * goods_number) " .
                " as amount FROM " . C('DB_PREFIX') .
                "cart WHERE " .
                " rec_type = '$type' ".
                " and rec_id ".db_create_in($rec_ids);


        if (!$include_gift) {
            $sql .= ' AND is_gift = 0 AND goods_id > 0';
        }
        $res = M()->query($sql);
        return floatval($res[0]['amount']);
        
    }
    /**
     * 设置红包为已使用
     * @param   int     $bonus_id   红包id
     * @param   int     $order_id   订单id
     * @return  bool
     */
    function use_bonus($bonus_id, $order_id) {
        $sql = "UPDATE " . C('DB_PREFIX') .
                "user_bonus SET order_id = '$order_id', used_time = '" . gmtime() . "' " .
                "WHERE bonus_id = '$bonus_id' LIMIT 1";

        return M()->execute($sql);
    }


 /**
     * 改变订单中商品库存
     * @param   int     $order_id   订单号
     * @param   bool    $is_dec     是否减少库存
     * @param   bool    $storage     减库存的时机，1，下订单时；0，发货时；
     */
    function change_order_goods_storage($order_id, $is_dec = true, $storage = 0) {
        /* 查询订单商品信息 */
        switch ($storage) {
            case 0 :
                $sql = "SELECT goods_id, SUM(send_number) AS num, MAX(extension_code) AS extension_code, product_id FROM " . C('DB_PREFIX') .
                        "order_goods WHERE order_id = '$order_id' AND is_real = 1 GROUP BY goods_id, product_id";
                break;

            case 1 :
                $sql = "SELECT goods_id, SUM(goods_number) AS num, MAX(extension_code) AS extension_code, product_id FROM " . C('DB_PREFIX') .
                        "order_goods WHERE order_id = '$order_id' AND is_real = 1 GROUP BY goods_id, product_id";
                break;
        }

        $res = M()->query($sql);
        foreach ($res as $row) {
            if ($row['extension_code'] != "package_buy") {
                if ($is_dec) {
                    $this->change_goods_storage($row['goods_id'], $row['product_id'], - $row['num']);
                } else {
                    $this->change_goods_storage($row['goods_id'], $row['product_id'], $row['num']);
                }
                M()->query($sql);
            } 
            else {
                $sql = "SELECT goods_id, goods_number" .
                        " FROM " .C('DB_PREFIX') .
                        "package_goods WHERE package_id = '" . $row['goods_id'] . "'";
                $list=M()->query($sql);
                $row_goods = $list[0];
                $sql = "SELECT is_real" .
                        " FROM " . C('DB_PREFIX') .
                        "goods WHERE goods_id = '" . $row_goods['goods_id'] . "'";
                $list=M()->query($sql);
                $is_goods = $list[0];

                if ($is_dec) {
                    $this->change_goods_storage($row_goods['goods_id'], $row['product_id'], - ($row['num'] * $row_goods['goods_number']));
                } elseif ($is_goods['is_real']) {
                    $this->change_goods_storage($row_goods['goods_id'], $row['product_id'], ($row['num'] * $row_goods['goods_number']));
                }
            }

            //加销量
            if($row_goods['goods_number']>0)
            {
              $status2=M('touch_goods')->where($where)->setInc('sales_volume',$row_goods['goods_number']);
            }
        }
    }
/**
     * 商品库存增与减 货品库存增与减
     *
     * @param   int    $good_id         商品ID
     * @param   int    $product_id      货品ID
     * @param   int    $number          增减数量，默认0；
     *
     * @return  bool               true，成功；false，失败；
     */
    function change_goods_storage($good_id, $product_id, $number = 0) {
        if ($number == 0) {
            return true; // 值为0即不做、增减操作，返回true
        }

        if (empty($good_id) || empty($number)) {
            return false;
        }

        $number = ($number > 0) ? '+ ' . $number : $number;

        /* 处理货品库存 */
        $products_query = true;
        if (!empty($product_id)) {
            $sql = "UPDATE " . C('DB_PREFIX') .
                    "products SET product_number = product_number $number
                WHERE goods_id = '$good_id'
                AND product_id = '$product_id'
                LIMIT 1";
            $products_query = M()->execute($sql);
        }

        /* 处理商品库存 */
        $sql = "UPDATE " . C('DB_PREFIX') .
                "goods SET goods_number = goods_number $number
            WHERE goods_id = '$good_id'
            LIMIT 1";
        $query =  M()->execute($sql);

        if ($query && $products_query) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 处理红包（下订单时设为使用，取消（无效，退货）订单时设为未使用
     * @param   int     $bonus_id   红包编号
     * @param   int     $order_id   订单号
     * @param   int     $is_used    是否使用了
     */
    function change_user_bonus($bonus_id, $order_id, $is_used = true) {
        if ($is_used) {
            $sql = 'UPDATE ' . C("DB_PREFIX"). 'user_bonus SET ' .
                    'used_time = ' . gmtime() . ', ' .
                    "order_id = '$order_id' " .
                    "WHERE bonus_id = '$bonus_id'";
        } else {
            $sql = 'UPDATE ' . C("DB_PREFIX") . 'user_bonus SET ' .
                    'used_time = 0, ' .
                    'order_id = 0 ' .
                    "WHERE bonus_id = '$bonus_id'";
        }
        M()->execute($sql);
    }




}
?>

